package com.macro.mall.tiny.modules.oms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.macro.mall.tiny.modules.oms.dto.OrderCreateParam;
import com.macro.mall.tiny.modules.oms.dto.OrderQueryParam;
import com.macro.mall.tiny.modules.oms.dto.OrderUpdateAmountParam;
import com.macro.mall.tiny.modules.oms.dto.OrderUpdateStatusParam;
import com.macro.mall.tiny.modules.oms.enums.OrderStatusEnum;
import com.macro.mall.tiny.modules.oms.vo.OrderListVO;
import com.macro.mall.tiny.modules.oms.mapper.OrderMapper;
import com.macro.mall.tiny.modules.oms.mapper.OrderGoodsMapper;
import com.macro.mall.tiny.modules.oms.mapper.OrderLogMapper;
import com.macro.mall.tiny.modules.oms.model.Order;
import com.macro.mall.tiny.modules.oms.model.OrderGoods;
import com.macro.mall.tiny.modules.oms.model.OrderLog;
import com.macro.mall.tiny.modules.oms.service.OrderService;
import com.macro.mall.tiny.modules.oms.service.CartService;
import com.macro.mall.tiny.security.util.JwtTokenUtil;
import com.macro.mall.tiny.modules.pms.model.ProductSku;
import com.macro.mall.tiny.modules.pms.service.ProductSkuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderGoodsMapper orderGoodsMapper;

    @Autowired
    private OrderLogMapper orderLogMapper;

    @Autowired
    private CartService cartService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private ProductSkuService productSkuService;
    
    @Override
    @Transactional
    public String createOrder(OrderCreateParam orderCreateParam) {
        Integer userId = orderCreateParam.getUserId();
        
        // 如果参数中没有userId，尝试从token中解析
        if (userId == null && orderCreateParam.getToken() != null) {
            try {
                String userIdStr = jwtTokenUtil.getUserNameFromToken(orderCreateParam.getToken());
                if (userIdStr != null && !userIdStr.isEmpty()) {
                    userId = Integer.parseInt(userIdStr);
                }
            } catch (Exception e) {
                throw new RuntimeException("无效的token");
            }
        }

        // 检查userId是否有效
        if (userId == null) {
            throw new RuntimeException("用户ID不能为空");
        }

        // 获取订单商品列表
        List<OrderCreateParam.OrderSkuParam> skuList = orderCreateParam.getSkuList();
        if (CollectionUtils.isEmpty(skuList)) {
            return null;
        }

        // 生成订单号
        String orderNo = generateOrderNo("S");

        // 创建订单商品列表和计算总金额
        int totalAmount = 0;
        
        // 创建订单商品
        for (OrderCreateParam.OrderSkuParam skuParam : skuList) {
            // 从商品表获取商品详细信息
            ProductSku productSku = productSkuService.getById(skuParam.getSkuId());
            if (productSku == null) {
                throw new RuntimeException("商品SKU不存在: " + skuParam.getSkuId());
            }

            OrderGoods orderGoods = new OrderGoods();
            orderGoods.setOrderNo(orderNo);
            orderGoods.setUserId(userId);
            orderGoods.setSkuId(skuParam.getSkuId());
            orderGoods.setQty(skuParam.getQty());
            orderGoods.setRemark(skuParam.getRemark());
            
            // 从商品实体中获取商品信息
            orderGoods.setSkuCode(productSku.getSkuCode());
            orderGoods.setTitle(productSku.getTitle());
            orderGoods.setMainImg(productSku.getMainImg());
            orderGoods.setCrossedPrice(productSku.getCrossedPrice());
            orderGoods.setPrice(productSku.getPrice());
            
            orderGoods.setCreatedAt(LocalDateTime.now());
            orderGoods.setUpdatedAt(LocalDateTime.now());
            orderGoods.setDelFlag(0);
            orderGoodsMapper.insert(orderGoods);

            // 计算总金额 (单价 * 数量)
            if (productSku.getPrice() != null && skuParam.getQty() != null) {
                totalAmount += productSku.getPrice().multiply(new BigDecimal(skuParam.getQty())).intValue();
            }
        }

        // 创建订单
        Order order = new Order();
        order.setOrderNo(orderNo);
        order.setOrderStatus(0); // 待处理
        order.setUserId(userId);
        order.setPayAmount(totalAmount);
        order.setRemark(orderCreateParam.getRemark());
        order.setCreatedAt(LocalDateTime.now());
        order.setUpdatedAt(LocalDateTime.now());
        order.setDelFlag(0);
        orderMapper.insert(order);

        // 创建订单日志
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderNo(orderNo);
        orderLog.setContent("创建订单");
        orderLog.setCreatedAt(LocalDateTime.now());
        orderLog.setUpdatedAt(LocalDateTime.now());
        orderLog.setDelFlag(0);
        orderLogMapper.insert(orderLog);

        // 将购物车中已下单的商品标记为已删除
        List<Integer> skuIds = skuList.stream()
                .map(OrderCreateParam.OrderSkuParam::getSkuId)
                .collect(Collectors.toList());
        cartService.deleteByUserIdAndSkuIds(userId, skuIds);

        return orderNo;
    }


    @Override
    public List<Order> getOrderList(OrderQueryParam queryParam) {
        // 根据查询参数构建查询条件
        // 这里需要修改 OrderMapper 以支持更多查询条件
        return orderMapper.getOrderList(queryParam);
    }

    @Override
    public Order getOrderDetail(String orderNo) {
        return getOne(new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<Order>()
                .eq(Order::getOrderNo, orderNo)
                .eq(Order::getDelFlag, 0));
    }

    @Override
    public List<OrderGoods> getOrderGoodsByOrderNo(String orderNo) {
        return orderGoodsMapper.getOrderGoodsByOrderNo(orderNo);
    }

    @Override
    public List<OrderLog> getOrderLogsByOrderNo(String orderNo) {
        return orderLogMapper.getOrderLogsByOrderNo(orderNo);
    }

    @Override
    public Page<OrderListVO> getUserOrderList(OrderQueryParam queryParam) {
        // 设置默认分页参数
        if (queryParam.getPageNum() == null || queryParam.getPageNum() <= 0) {
            queryParam.setPageNum(1);
        }
        if (queryParam.getPageSize() == null || queryParam.getPageSize() <= 0) {
            queryParam.setPageSize(10);
        }

        // 构建分页对象
        Page<Order> orderPage = new Page<>(queryParam.getPageNum(), queryParam.getPageSize());
        orderPage.setSearchCount(true); // 启用总记录数查询

        // 构建查询条件
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getUserId, queryParam.getUserId())
                .eq(Order::getDelFlag, 0);

        // 订单状态筛选
        if (queryParam.getOrderStatus() != null) {
            wrapper.eq(Order::getOrderStatus, queryParam.getOrderStatus());
        }

        // 时间范围筛选
        if (queryParam.getCreateTimeStart() != null) {
            wrapper.ge(Order::getCreatedAt, queryParam.getCreateTimeStart());
        }
        if (queryParam.getCreateTimeEnd() != null) {
            wrapper.le(Order::getCreatedAt, queryParam.getCreateTimeEnd());
        }

        // 按创建时间倒序排列
        wrapper.orderByDesc(Order::getCreatedAt);

        // 执行分页查询
        Page<Order> orderResultPage = page(orderPage, wrapper);

        // 获取订单列表
        List<Order> orderList = orderResultPage.getRecords();

        // 转换为用户端订单列表VO
        List<OrderListVO> orderVOList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(orderList)) {
            // 提取所有订单编号
            List<String> orderNos = orderList.stream()
                    .map(Order::getOrderNo)
                    .collect(Collectors.toList());

            // 批量获取订单商品信息
            Map<String, List<OrderGoods>> orderGoodsMap = new HashMap<>();
            if (!CollectionUtils.isEmpty(orderNos)) {
                LambdaQueryWrapper<OrderGoods> goodsWrapper = new LambdaQueryWrapper<>();
                goodsWrapper.in(OrderGoods::getOrderNo, orderNos);
                List<OrderGoods> orderGoodsList = orderGoodsMapper.selectList(goodsWrapper);
                
                // 按订单编号分组
                orderGoodsMap = orderGoodsList.stream()
                        .collect(Collectors.groupingBy(OrderGoods::getOrderNo));
            }

            // 转换为VO对象
            for (Order order : orderList) {
                OrderListVO orderVO = new OrderListVO();
                orderVO.setOrderNo(order.getOrderNo());
                orderVO.setOrderStatus(order.getOrderStatus());
                orderVO.setCreatedAt(order.getCreatedAt());
                
                // 计算订单商品总数量和第一个商品图片
                List<OrderGoods> goodsList = orderGoodsMap.get(order.getOrderNo());
                if (!CollectionUtils.isEmpty(goodsList)) {
                    int totalQty = goodsList.stream()
                            .mapToInt(goods -> goods.getQty() != null ? goods.getQty() : 0)
                            .sum();
                    orderVO.setTotalQty(totalQty);
                    
                    // 获取第一个商品的图片
                    OrderGoods firstGoods = goodsList.get(0);
                    orderVO.setFirstProductImage(firstGoods.getMainImg());
                }
                
                orderVOList.add(orderVO);
            }
        }
        
        // 构建返回的分页对象
        Page<OrderListVO> resultPage = new Page<>(orderResultPage.getCurrent(), orderResultPage.getSize(), orderResultPage.getTotal());
        resultPage.setRecords(orderVOList);
        
        return resultPage;
    }

    private String generateOrderNo(String prefix) {
        // 标识+年月日时分秒+4位随机数
        String dateTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        Random random = new Random();
        int randomNumber = 1000 + random.nextInt(9000); // 4位随机数
        return prefix + dateTime + randomNumber;
    }

    @Override
    @Transactional
    public boolean updateOrderAmount(OrderUpdateAmountParam updateAmountParam) {
        String orderNo = updateAmountParam.getOrderNo();
        BigDecimal newAmount = updateAmountParam.getPayAmount();
        String remark = updateAmountParam.getRemark();
        
        // 校验金额不能为负数
        if (newAmount.compareTo(BigDecimal.ZERO) < 0) {
            throw new RuntimeException("支付金额不能为负数");
        }
        
        // 获取订单
        Order order = getOne(new LambdaQueryWrapper<Order>()
                .eq(Order::getOrderNo, orderNo)
                .eq(Order::getDelFlag, 0));
        
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        
        Integer currentAmount = order.getPayAmount();
        
        // 更新订单金额
        order.setPayAmount(newAmount.intValue());
        order.setUpdatedAt(LocalDateTime.now());
        boolean updated = updateById(order);
        
        if (updated) {
            // 记录订单日志
            OrderLog orderLog = new OrderLog();
            orderLog.setOrderNo(orderNo);
            orderLog.setContent(String.format("订单金额从 %d 变更为 %d，备注：%s", currentAmount, newAmount.intValue(), remark != null ? remark : ""));
            orderLog.setCreatedAt(LocalDateTime.now());
            orderLog.setUpdatedAt(LocalDateTime.now());
            orderLog.setDelFlag(0);
            orderLogMapper.insert(orderLog);
        }
        
        return updated;
    }

    @Override
    @Transactional
    public boolean updateOrderStatus(OrderUpdateStatusParam updateStatusParam) {
        String orderNo = updateStatusParam.getOrderNo();
        Integer newStatus = updateStatusParam.getOrderStatus();
        String remark = updateStatusParam.getRemark();
        
        // 获取订单
        Order order = getOne(new LambdaQueryWrapper<Order>()
                .eq(Order::getOrderNo, orderNo)
                .eq(Order::getDelFlag, 0));
        
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        
        Integer currentStatus = order.getOrderStatus();
        
        // 验证状态流转是否合法
        if (!isValidStatusTransition(currentStatus, newStatus)) {
            throw new RuntimeException("订单状态流转不合法");
        }
        
        // 更新订单状态
        order.setOrderStatus(newStatus);
        order.setUpdatedAt(LocalDateTime.now());
        boolean updated = updateById(order);
        
        if (updated) {
            // 记录订单日志
            OrderLog orderLog = new OrderLog();
            orderLog.setOrderNo(orderNo);
            String currentStatusDesc = OrderStatusEnum.getDescriptionByCode(currentStatus);
            String newStatusDesc = OrderStatusEnum.getDescriptionByCode(newStatus);
            orderLog.setContent(String.format("订单从 %s 变更为 %s，备注：%s", currentStatusDesc, newStatusDesc, remark != null ? remark : ""));
            orderLog.setCreatedAt(LocalDateTime.now());
            orderLog.setUpdatedAt(LocalDateTime.now());
            orderLog.setDelFlag(0);
            orderLogMapper.insert(orderLog);
        }
        
        return updated;
    }
    
    /**
     * 验证订单状态流转是否合法
     * 0-询价，1-报价，2-设计，3-制作，4-配送/安装，5-结算资料对接，6-等待付款，7-已完成，8-已废弃
     * 0-7逐个状态流转，0-7都可以流转到8，其他的不可以流转
     * 
     * @param currentStatus 当前状态
     * @param newStatus 新状态
     * @return 是否合法
     */
    private boolean isValidStatusTransition(Integer currentStatus, Integer newStatus) {
        // 如果当前状态和新状态相同，不需要更新
        if (currentStatus.equals(newStatus)) {
            return true;
        }
        
        // 任何状态都可以流转到已废弃(8)
        if (newStatus == 8) {
            return true;
        }
        
        // 0-7状态必须逐个流转
        if (currentStatus >= 0 && currentStatus <= 7 && newStatus >= 0 && newStatus <= 7) {
            return newStatus - currentStatus == 1;
        }
        
        // 其他情况不合法
        return false;
    }
}
